<?php

namespace app\topics\middle;

class SearchMiddle extends \app\base\middle\BaseMiddle {


    protected function meta() {
        $this->setMeta('搜索');
        $this->setName('搜索');
        $this->setCrumb([
            [
                'name' => '搜索',
                'url' => url()
            ]
        ]);

        return $this->run([
            'pageInfo' => $this->pageInfo
        ]);
    }

    protected function data() {
        $keyword = urldecode($this->params['keyword']);
        $keyword = str_len(html_clear($keyword), 100, false);


        if(empty($keyword)) {
            return $this->stop('关键词不存在!');
        }

        $keywords = explode(' ', $keyword);
        $keywords = array_filter($keywords);

        if(empty($keywords)) {
            return $this->stop('关键词不存在!');
        }

        $keywords = target('topics/TopicsSearch')->splitKeywords(implode('', $keywords));

        $str = '+';

        $sql = [];

        $pingyin = new \dux\lib\Pinyin();
        foreach ($keywords as $vo) {
            $sql[] = "LOCATE('$vo', 'markdown') != 0 ";
            $str .= $pingyin->output($vo). " ";
        }
        $str = trim($str);

        $pageParams = [];
        $where = [];

        $pageParams['keyword'] = $keyword;


        $pageLimit = 20;


        $model = target('topics/TopicsDetail');
        $list = $model->query("SELECT detail_id, MATCH(search) AGAINST ('$str' in boolean mode) as score FROM {pre}topics_search WHERE MATCH(search) AGAINST ('$str' in boolean mode) ORDER BY score desc, detail_id desc; ");

        $detail = [];
        foreach ($list as $vo) {
            $detail[] = $vo['detail_id'];
        }
        if ($detail) {
            $where['_sql'] = 'A.detail_id in (' . implode(',', $detail) . ')';
            $count = $model->countList($where);
            $pageData = $this->pageData($count, $pageLimit);
            $list = $model->loadList($where, $pageData['limit'], 'instr(\'' . implode(',', $detail) . '\',detail_id)');
        } else {
            $pageData = [];
            $list = [];
            $count = 0;
        }
        foreach ($list as $key => $vo) {
            $list[$key]['title'] = $this->highlight($vo['title'], $keywords);
            $list[$key]['description'] = $this->highlight($vo['description'], $keywords);

        }
        return $this->run([
            'pageData' => $pageData,
            'countList' => $count,
            'pageList' => $list,
            'keyword' => $keyword,
            'pageParams' => $pageParams
        ]);
    }

    private function highlight($str, $keywords) {
        foreach ($keywords as $vo) {
            $str = str_ireplace($vo, "<span class='highlight'>".$vo."</span>", $str);
        }
        return $str;
    }


}